package com.example.web.webauth.service;

import com.alibaba.fastjson.JSON;
import com.example.web.webauth.dao.UserDao;
import com.example.web.webauth.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserDao userDao;

    //根据 账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("loadUserByUsername >>>");
        //将来连接数据库根据账号查询用户信息
        UserDto userDto = userDao.getUserByUsername(username);
        if (userDto == null) {
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        userDto.setRole(userDao.getRoleByUserId(userDto.getUserId()));

        //根据用户的id查询用户的权限
        List<String> permissions = userDao.findPermissionsByUserId(userDto.getUserId());
        //将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        //密码
        String password = userDto.getPassword();
        //将userDto转成json
        userDto.setPassword(null);
        String principal = null;
        try {
            principal = URLEncoder.encode(JSON.toJSONString(userDto), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        UserDetails userDetails = User.withUsername(principal).password(password).authorities(permissionArray).build();
        return userDetails;
    }
}
